package evan.curtis.pi_player;

import java.io.IOException;
import java.io.InputStream;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

import evan.curtis.pi_player.util.SSHCommands;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ActionBar.Tab;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

	private ActionBar actionBar;
	private PiFilesFragment mPiFilesFragment;
	private LocalFilesFragment mLocalFilesFragment;
	private PandoraFragment mPandoraFragment;
	public int volumeLevel = 0;
	private static Session session;
	public boolean pianobarConnected = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		new sshConnect().execute();

		actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		String label = getResources().getString(R.string.pi_files);
		Tab tab = actionBar.newTab();
		tab.setText(label);
		TabListener<PiFilesFragment> tl0 = new TabListener<PiFilesFragment>(
				this, label, PiFilesFragment.class);
		tab.setTabListener(tl0);
		actionBar.addTab(tab);

		tab.select();
		mPiFilesFragment = (PiFilesFragment) tl0.mFragment;

		// --------------------------------------------------------------------------------/
		//
		// label = getResources().getString(R.string.local_files);
		// tab = actionBar.newTab();
		// tab.setText(label);
		// TabListener<LocalFilesFragment> tl1 = new
		// TabListener<LocalFilesFragment>(
		// this, label, LocalFilesFragment.class);
		// tab.setTabListener(tl1);
		// actionBar.addTab(tab);
		// tab.select();
		// mLocalFilesFragment = (LocalFilesFragment) tl1.mFragment;

		// --------------------------------------------------------------------------------/

		label = getResources().getString(R.string.pandora);
		tab = actionBar.newTab();
		tab.setText(label);
		TabListener<PandoraFragment> tl2 = new TabListener<PandoraFragment>(
				this, label, PandoraFragment.class);
		tab.setTabListener(tl2);
		actionBar.addTab(tab);
		tab.select();
		mPandoraFragment = (PandoraFragment) tl2.mFragment;

		// return action bar to first tab
		tab = actionBar.getTabAt(0);
		tab.select();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		int action = event.getAction();
		int keyCode = event.getKeyCode();
		switch (keyCode) {
		case KeyEvent.KEYCODE_VOLUME_UP:
			if (action == KeyEvent.ACTION_UP) {
				new sshTask().execute("amixer -c 0 -- sset PCM playback 3dB+");
			}
			return true;
		case KeyEvent.KEYCODE_VOLUME_DOWN:
			if (action == KeyEvent.ACTION_DOWN) {
				new sshTask().execute("amixer -c 0 -- sset PCM playback 3dB-");
			}
			return true;
		default:
			return super.dispatchKeyEvent(event);
		}
	}

	private class TabListener<T extends Fragment> implements
			ActionBar.TabListener {
		private Fragment mFragment;
		private final Activity mActivity;
		private final String mTag;
		private final Class<T> mClass;

		public TabListener(Activity activity, String tag, Class<T> clz) {
			mActivity = activity;
			mTag = tag;
			mClass = clz;
		}

		public void onTabSelected(Tab tab, FragmentTransaction ft) {
			// Check if the fragment is already initialized
			if (mFragment == null) {
				// If not, instantiate and add it to the activity
				mFragment = Fragment.instantiate(mActivity, mClass.getName());
				ft.add(android.R.id.content, mFragment, mTag);
			} else {
				// If it exists, simply attach it in order to show it
				ft.attach(mFragment);
			}
		}

		public void onTabUnselected(Tab tab, FragmentTransaction ft) {
			if (mFragment != null) {
				// Detach the fragment, because another one is being attached
				ft.detach(mFragment);
			}
		}

		public void onTabReselected(Tab tab, FragmentTransaction ft) {
			// User selected the already selected tab. Usually do nothing.
		}
	}

	// private void sshConnect() throws JSchException {
	//
	// String host = "192.168.1.4";
	// String user = "pi";
	// String pwd = "Kg7$m4";
	// int port = 22;
	//
	// java.util.Properties config = new java.util.Properties();
	// config.put("StrictHostKeyChecking", "no");
	// JSch jsch = new JSch();
	// session = jsch.getSession(user, host, port);
	// session.setPassword(pwd);
	// session.setConfig(config);
	// session.connect();
	// Log.i("sshConnect", "Connected");
	//
	// }

	public String sshCommand(String command) throws JSchException, IOException {

		String result = "";

		// String host = "192.168.1.4";
		// String user = "pi";
		// String pwd = "Kg7$m4";
		// int port = 22;
		//
		// java.util.Properties config = new java.util.Properties();
		// config.put("StrictHostKeyChecking", "no");
		// JSch jsch = new JSch();
		// Session session = jsch.getSession(user, host, port);
		// session.setPassword(pwd);
		// session.setConfig(config);
		// session.connect();
		// Log.i("SSH", "Connected");

		Channel channel = session.openChannel("exec");
		((ChannelExec) channel).setCommand(command);
		channel.setInputStream(null);
		((ChannelExec) channel).setErrStream(System.err);
		InputStream in = channel.getInputStream();

		channel.connect();

		byte[] tmp = new byte[1024];

		// wait for output if needed
		if (command.equals("cd Music\nls")
				|| command.equals("amixer -c 0 -- sset PCM playback 3dB+")
				|| command.equals("amixer -c 0 -- sset PCM playback 3dB-")
				|| command.equals(SSHCommands.READ_PIANOBAR_EVENTS)) {
			while (true) {
				while (in.available() > 0) {
					int i = in.read(tmp, 0, 1024);
					if (i < 0)
						break;
					result += new String(tmp, 0, i);
	
				}
				if (channel.isClosed()) {
					Log.i("exit-status: ",
							Integer.toString(channel.getExitStatus()));
					break;
				}
				try {
					Thread.sleep(1000);
				} catch (Exception ee) {
				}
				// }
			}

			channel.disconnect();
			// session.disconnect();
			Log.i("SSH", "done");

		}

		return result;

	}

	// public void handleEvent(View v) {
	//
	// switch (v.getId()) {
	// case R.id.playButton:
	// new sshTask().execute("cd Music\nmpg321 Arrive.mp3");
	// break;
	// case R.id.stopButton:
	// new sshTask().execute("pkill -SIGHUP mpg321");
	// break;
	// case R.id.volumePlus:
	// new sshTask().execute("amixer -c 0 -- sset PCM playback 3dB+");
	// break;
	// case R.id.volumeMinus:
	// new sshTask().execute("amixer -c 0 -- sset PCM playback 3dB-");
	// break;
	// }
	//

	// The definition of our task class
	public class sshTask extends AsyncTask<String, Integer, String> {

		String command = "";

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

		}

		@Override
		protected String doInBackground(String... params) {
			String task = params[0];
			command = task;
			String s = "";
			try {
				s = sshCommand(task);

			} catch (JSchException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Log.i("iofail", "fail");
				e.printStackTrace();
			}

			return s;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);

		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);

			String[] results = result.split("\n");

			// get volume level
			if (results.length >= 4) {
				int end = results[4].indexOf("%");
				int begin = results[4].indexOf("[") + 1;
				String volume = results[4].substring(begin, end);
				Toast.makeText(getApplicationContext(), "Volume: " + volume +
				 "%", Toast.LENGTH_SHORT).show();
				volumeLevel = Integer.parseInt(volume);
			}

		}

	}

	public class sshConnect extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... arg0) {
			String host = "192.168.1.4";
			String user = "pi";
			String pwd = "Kg7$m4";
			int port = 22;

			java.util.Properties config = new java.util.Properties();
			config.put("StrictHostKeyChecking", "no");
			JSch jsch = new JSch();
			try {
				session = jsch.getSession(user, host, port);
			} catch (JSchException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			session.setPassword(pwd);
			session.setConfig(config);
			try {
				session.connect();
			} catch (JSchException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Log.i("sshConnect", "Connected");
			return null;
		}

	}

}
